package com.yinp.proapp.module.study.recycler;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

/**
 * @author :yinpeng
 * date      :2021/8/30
 * package   :com.yinp.proapp.module.study.recycler
 * describe  :
 */
public class MRecyclerView extends RecyclerView {
    public MRecyclerView(@NonNull Context context) {
        super(context);
    }

    public MRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public MRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private int mTouchSlop;
    private int mScrollPointerId = 0;
    private int mInitialTouchX;
    private int mInitialTouchY;

    @Override
    public boolean onInterceptTouchEvent(MotionEvent e) {
        //仿造源码
        final int action = e.getAction();
        final int actionIndex = e.getActionIndex();
        switch (action) {
            case MotionEvent.ACTION_DOWN://记录按下的坐标
                mScrollPointerId = e.getPointerId(0);
                mInitialTouchX = (int) (e.getX() + 0.5f);
                mInitialTouchY = (int) (e.getY() + 0.5f);
                break;
            case MotionEvent.ACTION_POINTER_DOWN://这边处理多手指触摸，优先使用后面触摸的手指
                mScrollPointerId = e.getPointerId(actionIndex);
                mInitialTouchX = (int) (e.getX() + 0.5f);
                mInitialTouchY = (int) (e.getY() + 0.5f);
                break;
            case MotionEvent.ACTION_MOVE://仿造源码
                final int index = e.findPointerIndex(mScrollPointerId);
                final int x = (int) (e.getX(index) + 0.5f);
                final int y = (int) (e.getY(index) + 0.5f);

                boolean startScroll = false;
                if (getScrollState() != SCROLL_STATE_DRAGGING) {
                    final int dx = x - mInitialTouchX;
                    final int dy = y - mInitialTouchY;

                    //这边增加拦截的难度，当滑动的水平距离大于滑动的垂直距离时，才拦截，当然了，如果自身又能竖直滑动的情况，就不判断两个滑动距离大小
                    if ((getLayoutManager().canScrollHorizontally() && Math.abs(dx) > mTouchSlop)
                            && (getLayoutManager().canScrollVertically() || Math.abs(dx) > Math.abs(dy))) {
                        startScroll = true;
                    }
                    //这里是当滑动的水平距离小于滑动的垂直距离时，才拦截，如果自身又能水平滑动的情况，就不判断两个滑动距离大小
                    if ((getLayoutManager().canScrollVertically() && Math.abs(dy) > mTouchSlop)
                            && (getLayoutManager().canScrollHorizontally() || Math.abs(dy) > Math.abs(dx))) {
                        startScroll = true;
                    }
                }

                return startScroll && super.onInterceptTouchEvent(e);
        }

        return super.onInterceptTouchEvent(e);
    }
}
